package cn.sc.summer.feign.config;

import cn.sc.summer.token.service.EncryptService;
import feign.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;

/**
 * 类名：openfeign返回结果解析
 *
 * @author a-xin
 * @date 2024/5/13 13:39
 */
@Slf4j
@Configuration
public class FeignResponseConfig extends SpringDecoder {

    @Resource
    private EncryptService encryptService;

    public FeignResponseConfig(ObjectFactory<HttpMessageConverters> messageConverters) {
        super(messageConverters);
    }

    @Override
    public Object decode(final Response response, Type type) throws IOException {
        Response.Body body = response.body();
        String bodyString = IOUtils.toString(body.asReader(StandardCharsets.UTF_8)).replaceAll("\"", "");
        String resultStr = encryptService.decryptFeignData(StringEscapeUtils.unescapeJava(bodyString));
        return super.decode(response.toBuilder().body(resultStr, StandardCharsets.UTF_8).build(), type);
    }

}
